package com.jet.chat.command;

import java.util.regex.Matcher;

import com.jet.chat.dbquery.ChatQueryAddHistory;
import com.jet.chat.dbquery.ChatQueryAddHistoryParams;
import com.jet.chat.dbquery.ChatQueryUsers;
import com.jet.chat.dbquery.ChatQueryUsersResult;
import com.jet.chat.message.Message;
import com.jet.chat.server.ChatServer;
import com.jet.chat.server.ChatSession;


public class ChatCommandWhisper extends ChatCommandAbstract {
	public ChatCommandWhisper() {
		super("^/\\w+\\s(\\w+)\\s(.*)$");
	}

	@Override
	protected void executeCommand(Matcher matcher, ChatServer chatServer, ChatSession chatSession, Message chatMessage) throws Exception {
		
		chatMessage.setContent(matcher.group(2));
		String recieverUsername = matcher.group(1);
		ChatQueryUsersResult users = (ChatQueryUsersResult) new ChatQueryUsers().execute(chatServer.getDBConnectionService(), null);
		
		if (users.getUsers().containsKey(recieverUsername)) {
			new ChatQueryAddHistory().execute(chatServer.getDBConnectionService(), new ChatQueryAddHistoryParams(chatSession.getUserId(), users.getUsers().get(recieverUsername), chatSession.getChannelName(), chatMessage));
			
			ChatSession recieverSession = chatServer.getChannel(chatSession.getChannelName()).getSession(recieverUsername);
			if (recieverSession == null ) {
				chatSession.getQueue().addMessage("server > no such reciever online. message will be stored");
			} else {
				chatMessage.setContent(chatSession.getUsername() + " whispers: " + matcher.group(2));
				recieverSession.getQueue().addMessage(chatMessage);
			}
		} else {
			chatSession.getQueue().addMessage("server > no such reciever registered");
		}
		
	}

}
